package com.hb.trade.server.project.section.controller;

import cn.hutool.core.collection.CollUtil;
import com.hb.core.pojo.parent.PageResult;
import com.hb.core.pojo.project.section.dto.InquiryDTO;
import com.hb.core.pojo.project.section.entity.InquiryReply;
import com.hb.trade.server.project.section.manager.InquiryManager;
import com.hb.trade.server.project.section.service.raw.InquiryReplyService;
import com.hb.trade.server.project.section.service.raw.InquiryService;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.MsgUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author yyx
 * @date 2022/5/16
 * @desc 询标回复
 */
@RestController
public class InquiryController {

    protected final InquiryService inquiryService;
    protected final InquiryReplyService inquiryReplyService;

    public InquiryController(final InquiryService inquiryService, final InquiryReplyService inquiryReplyService) {
        this.inquiryService = inquiryService;
        this.inquiryReplyService = inquiryReplyService;
    }

    /**
     * 创建询标申请
     *
     * @param inquiryDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/inquiry/saveOrUpdateInquiry")
    public Message<Boolean> saveOrUpdateInquiry(@RequestBody final InquiryDTO inquiryDTO) {
        final InquiryManager manager = inquiryDTO.to(InquiryManager.class);
        final List<InquiryReply> inquiryReplys = manager.getInquiryReplys();
        final Long id = inquiryDTO.getId();
        if (id != null) {
            this.inquiryReplyService.deleteByInquiryId(id);
            //修改数据只能是组长
        }
        //在api层填充创建人和修改人ID
        //查询评委会数据，专家数据以及别的关联数据
        //专家申请：创建人是专家，修改人是专家组长，默认状态？
        //组长发起：创建人和修改人都是组长，默认状态？
        //询标
        boolean flag = this.inquiryService.saveOrUpdate(inquiryDTO);
        flag &= this.inquiryReplyService.saveBatch(inquiryReplys);
        return MsgUtil.success(flag);
    }

    /**
     * 询标回复列表
     *
     * @return
     */
    @PostMapping("/inquiry/listAll")
    public Message<PageResult<InquiryDTO>> listAll(@RequestBody final InquiryDTO inquiryDTO) {
        final PageResult<InquiryDTO> result = this.inquiryService.listAll(inquiryDTO);
        if (CollUtil.isEmpty(result.getRecords())) {
            return MsgUtil.fail(MsgEnum.NULL_RESULT.msg());
        }
        return MsgUtil.success(result);
    }

}
